<?php

/**
 * This is the model class for table "users".
 *
 * The followings are the available columns in table 'users':
 * @property integer $id
 * @property string $login
 * @property string $email
 * @property string $password
 * @property integer $role
 * @property integer $organization_id
 * @property integer $shop_id
 * @property string $created_at
 * @property string $updated_at
 * @property integer $active
 */
class Users extends CActiveRecord
{
	const SALT = '35cfc00244';

	const ADMIN_ROLE = 1;
	const MANAGER_ROLE = 2;
	const OPERATOR_ROLE = 3;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Users the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{users}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('login, password, role, organization_id, created_at', 'required'),
			array('role, organization_id, shop_id, active', 'numerical', 'integerOnly'=>true),
			array('login', 'length', 'min'=>4, 'max'=>20),
			array('password', 'length', 'min'=>6, 'max'=>50),
			array('password', 'match', 'pattern'=>'#^[A-Za-z0-9]+$#u','message'=>'Используйте только латиницу и цифры.'),
			array('email','email'),
			array('login','unique','message'=>'Такое имя пользователя уже занято.'),
			array('shop_id','operatorShop'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('login, role, organization_id', 'safe', 'on'=>'search'),
		);
	}

	public function operatorShop()
	{
		if($this->role == self::OPERATOR_ROLE and !$this->shop_id){
			$this->addError('shop_id','Оператор должен быть привязан к магазину.');
		}
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'organization' => array(self::BELONGS_TO,'Organizations','organization_id'),
			'shop' => array(self::BELONGS_TO,'Shops','shop_id')
		);
	}

	public function behaviors(){
		return array(
			'createUpdateBehavior' => array(
				'class' => 'application.behaviors.CreateDateBehavior',
				'createdField' => 'created_at'
			),
			'hashBehavior' => array(
				'class' => 'application.behaviors.HashBehavior',
				'field' => 'password'
			),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => '#',
			'login' => 'Логин',
			'email' => 'Email',
			'password' => 'Пароль',
			'role' => 'Должность',
			'organization_id' => 'Организация',
			'shop_id' => 'Магазин',
			'created_at' => 'Добавлен',
			'updated_at' => 'Обновлен',
			'active' => 'Активен',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('login',$this->login,true);
		$criteria->compare('role',$this->role);
		$criteria->compare('organization_id',$this->organization_id);

		$criteria->addCondition('role!='.Users::ADMIN_ROLE);
		$criteria->compare('t.active',1);

		if(Yii::app()->user->getState('role')==Users::MANAGER_ROLE){
			$criteria->addCondition('role='.Users::OPERATOR_ROLE);
			$criteria->compare('organization_id',Yii::app()->user->getState('organization_id'));
		}

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public static function getList($role = null, $organization_id = null)
	{
		$criteria = new CDbCriteria();
		$criteria->addCondition('role!='.Users::ADMIN_ROLE);

		if($role !== null)
			$criteria->compare('role',$role);

		if($organization_id !== null)
			$criteria->compare('t.organization_id',$organization_id);

		$criteria->with = array('organization','shop');

		return new CActiveDataProvider(self::model(),array(
			'criteria'=>$criteria
		));
	}

	public static function getRoleName($id)
	{
		$roles = array(
			1 => 'Администратор',
			2 => 'Управляющий',
			3 => 'Оператор'
		);

		return isset($roles[$id])?$roles[$id]:null;
	}
}